package play.coroutine.basics

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.cancel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.sql.Time
import java.time.LocalDateTime
import java.util.Date

fun test1() {
    runBlocking {
        try {
            withContext(Dispatchers.IO) {
                println("2")
                delay(1000)
                println("3")
                this.cancel()
                println("4")
            }
        } catch (e: Exception) {
            println(e)
        }

        var count = 0
        while (true) {
            if (count > 10) {
                break
            }
            count += 1
            delay(500)
            println(isActive)
        }
        println("1")
    }
}

suspend fun test2() {
    val channel = Channel<Unit>()
    CoroutineScope(Dispatchers.IO).launch {
        var count = 0
        while (isActive) {
            try {
                println(LocalDateTime.now())
                if (count > 10) {
                    channel.send(Unit)
                    this.cancel()
                }
                delay(300)
            } catch (e: Exception) {
                count += 1
                println("===> ${e.message}")
            }
        }
        println("-->cancel")
    }
    return channel.receive()
}

suspend fun test3(time:Int = 1) {
    withContext(Dispatchers.IO) {
        println("$time: ${LocalDateTime.now()}")
        delay(1000L*time)
        println("$time: ${LocalDateTime.now()}")
    }
}

fun main() {
    CoroutineScope(Dispatchers.Default).launch {
        test3()
    }
    runBlocking {
        test3()
        println("====")
        val a = async { test3(3) }
        val a2 = async { test3(5) }
        a.await()
        a2.await()
        println("over")
    }
}